package dome_013;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * <p>Description: [写时复制容器 copy on write
 * 多线程环境下，写时效率低，读时效率高
 * 适合写少读多的环境]</p>
 * Created on 2020/12/15
 *
 * @author <a href="mailto: 819712047@qq.com">谢振东 </a>
 * @version 1.0
 */
public class T03_SynchronizedList {
    public static void main(String[] args) {
        List<String> lists1 = new ArrayList<String>(); //这个会出并发问题
        List<String> lists2 = new Vector<String>();
        List<String> lists3 = new CopyOnWriteArrayList<String>();
        List<String> lists4 = Collections.synchronizedList(lists1); //此时的集合是同步的

//        test(lists1, "ArrayList");
        test(lists2, "Vector");
        test(lists3, "CopyOnWriteArrayList");
        test(lists4, "synchronizedList");
    }

    private static void test(List<String> lists, String name) {
        Random r = new Random();
        Thread[] threads = new Thread[100];
        for (int i = 0; i < threads.length; i++) {
            Runnable task = new Runnable() {
                @Override
                public void run() {
                    for (int j = 0; j < 1000; j++) {
                        lists.add("a" + r.nextInt(10000));
                    }
                }
            };
            threads[i] = new Thread(task);
        }


        long start = System.currentTimeMillis();
        runAndComputeTime(threads);
        long end = System.currentTimeMillis();
        System.out.println(String.format("[%s]-消耗时间:[%s] ms,长度:[%s]", name, (end - start), lists.size()));
    }

    private static void runAndComputeTime(Thread[] threads) {

        Arrays.asList(threads).forEach(t -> t.start());
        Arrays.asList(threads).forEach(t -> {
            try {
                t.join(); //join等线程执行完之后再往下执行
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}
